// 日志服务模块:把对话记录写道md文件
import fs from 'fs';
import path from 'path';
import { Message } from '../config/types';

export class ChatLogger {
  private readonly logDir: string;
  private readonly logFile: string;

  constructor() {
    this.logDir = path.join(__dirname, '..', 'tem_logs'); // 当前模块的上一个目录
    this.logFile = path.join(this.logDir, `chat_${this.getFormattedDate()}.md`);
    this.ensureDirExists();
  }

  private getFormattedDate(): string {
    return new Date().toISOString().slice(0, 10); // YYYY-MM-DD
  }

  // 确保目录存在
  private ensureDirExists(): void {
    if (!fs.existsSync(this.logDir)) {
      fs.mkdirSync(this.logDir, { recursive: true });
    }
  }

  private formatMessage(messages: Message[]): string {
    let md = `## 对话记录 ${new Date().toLocaleString()}\n\n`;
    
    messages.forEach((msg, index) => {
      const prefix = msg.role === 'user' ? '👤 **用户**' : '🤖 **助手**';
      md += `${prefix} \`${new Date().toLocaleTimeString()}\`\n\n` +
            `\`\`\`\n${msg.content}\n\`\`\`\n\n`;
      
      // 添加分隔线（最后一条除外）
      if (index < messages.length - 1) {
        md += '---\n\n';
      }
    });

    return md;
  }

  public async append(messages: Message[]): Promise<void> {
    try {
      const content = this.formatMessage(messages);
      // console.log('content',content)
      await fs.promises.appendFile(this.logFile, content + '\n\n');
    } catch (error: any) {
      console.error('⚠️ 日志写入失败:', error.message);
    }
  }
}
